﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text;

namespace XLDL.Includes
{
    public partial class GioHang1 : System.Web.UI.UserControl
    {
        StringBuilder tooltip = new StringBuilder();
        protected void Page_Load(object sender, EventArgs e)
        {
           if (!IsPostBack)
            {
                Session["ok"] = "";
                Session["tooltip"] =0;
                xuat_luoi();
             //   this.PreRender += new EventHandler(this.Page_Load);               
            }
           
        }
        private void xuat_luoi()
        {
            XL_Gio_hang bang_gio_hang = (XL_Gio_hang)Session["gio_hang"];
         

            // so sánh size trong database neu ko tim thay thi xoa san pham co size do trong gio hang
            DataTable tb = new DataTable();
            for (int i = 0; i < bang_gio_hang.Rows.Count; i++)
            {
                string id_sp = bang_gio_hang.Rows[i]["id_sp"].ToString();
                string so_size = bang_gio_hang.Rows[i]["so_size"].ToString();
                string lenh = "select * from V_size where id_sp=" + int.Parse(id_sp) + " and so_size='" + so_size + "'";
                tb = XLDL.XLDaTa(lenh);
                if (tb.Rows.Count == 0)
                {
                    bang_gio_hang.Rows.RemoveAt(i);
                }
            }
            // cap nhat STT
            int stt = 0;
            for (int i = 0; i < bang_gio_hang.Rows.Count; i++)
            {
                stt += 1;
                bang_gio_hang.Rows[i]["STT"] = stt;
            }
           // bang_gio_hang.DefaultView.Sort = "ID DESC";
            luoi_gio_hang.DataSource = bang_gio_hang;
            
          //  this.erorr.Visible = false;
          //  Submit.Enabled = true;
            luoi_gio_hang.DataBind();
            lbl_tongtien.Text = bang_gio_hang.Tong_tri_gia.ToString("#,##0 VNĐ");
        
            lbl_tongmathang.Text = bang_gio_hang.DefaultView.ToTable(true,"id_sp").Rows.Count.ToString();
            lbl_tongsoluong.Text = bang_gio_hang.Tong_tri_SoLuong.ToString();
            if (bang_gio_hang.Rows.Count == 0)
            {
                this.lbl_thongbao.Visible = true;
                this.Panel_thongtin.Visible = false;
                this.Panel_thanhtoan.Visible = false;
                Session["ok"] = "false";
            }
            //else
            //{
            if (Session["ok"].ToString() == "true")
            {
                this.Panel_thanhtoan.Visible = true;
            }
            else
            {
                this.Panel_thanhtoan.Visible = false;
            }
            
            // cap nhat lai gio hang
            GioHang gh=new GioHang();
             this.PreRender += new EventHandler(gh.GioHang_PreRender);
                                  
        }

        protected void luoi_gio_hang_RowEditing(object sender, GridViewEditEventArgs e)
        {

            try
            {
                luoi_gio_hang.EditIndex = e.NewEditIndex;
                xuat_luoi();
                // lay id_sp
                Label id = new Label();
                id = (Label)luoi_gio_hang.Rows[e.NewEditIndex].Cells[1].FindControl("lbl_id_sp");

                // do size vao dropdownlist thep id_sp
                DropDownList sosize = new DropDownList();
                sosize = (DropDownList)luoi_gio_hang.Rows[e.NewEditIndex].Cells[1].FindControl("drop_so_size");
                DataTable tb = new DataTable();
                tb = XLDL.XLDaTa("select * from V_size where id_SP=" + int.Parse(id.Text) + " order by so_size asc");
                sosize.DataSource = tb;
                sosize.DataTextField = "so_size";
                sosize.DataValueField = "id_size";
                sosize.DataBind();

                // txt size
                TextBox so_size = new TextBox();
                so_size = (TextBox)luoi_gio_hang.Rows[e.NewEditIndex].Cells[1].FindControl("txt_size");

                for (int i = 0; i <= sosize.Items.Count - 1; i++)
                {
                    if (sosize.Items[i].Text == so_size.Text)
                    {
                        sosize.SelectedIndex = i;
                    }
                }
            }
            catch { }

            //an label id_sp

          //  id.Visible = false;
     

           // GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
           // Label lblDate = (Label)row.Cells[1].FindControl("drop_id_sp");

          
        }

        protected void luoi_gio_hang_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            luoi_gio_hang.EditIndex = -1;
            xuat_luoi();
            
        }

        protected void luoi_gio_hang_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            try
            {
                //lay so luong nhap vao
                TextBox so_luong = (TextBox)luoi_gio_hang.Rows[e.RowIndex].Cells[2].FindControl("txt_soluong");
                XL_Gio_hang bang_gio_hang = (XL_Gio_hang)Session["gio_hang"];

                //int ms = (int)luoi_gio_hang.DataKeys[e.RowIndex]["ID"];
                // lay ma so id
                Label id = new Label();
                id = (Label)luoi_gio_hang.Rows[e.RowIndex].Cells[2].FindControl("lbl_id");
                DataRow dong = bang_gio_hang.Rows.Find(int.Parse(id.Text));
                //  dong["size"] = Session["size"].ToString();

                DropDownList sosize = new DropDownList();
                sosize = (DropDownList)luoi_gio_hang.Rows[e.RowIndex].Cells[1].FindControl("drop_so_size");
                dong["so_size"] = sosize.SelectedItem.ToString();
                dong["so_luong"] = int.Parse(so_luong.Text);


                Label id_sp = new Label();
                id_sp = (Label)luoi_gio_hang.Rows[e.RowIndex].Cells[1].FindControl("lbl_id_sp");

                //string sl1 = "";
                //string sl2 = "";
                int d = bang_gio_hang.Rows.Count;
                if (d != 0)
                {
                    int sl = 0;
                    int dem = 0;
                    for (int i = 0; i <= bang_gio_hang.Rows.Count - 1; i++)
                    {
                        if (bang_gio_hang.Rows[i]["so_size"].ToString() == sosize.SelectedItem.ToString() && bang_gio_hang.Rows[i]["id_sp"].ToString() == id_sp.Text)
                        {
                            sl = sl + (int)bang_gio_hang.Rows[i]["so_luong"];
                            dem++;
                        }
                        if (dem == 2)
                        {
                            // kiem tra so luong cua dong khac dong hien tai de xoa
                            for (i = 0; i <= bang_gio_hang.Rows.Count - 1; i++)
                            {
                                if (bang_gio_hang.Rows[i]["so_luong"].ToString() != sl.ToString())
                                {
                                    if (bang_gio_hang.Rows[i]["id_sp"].ToString() == id_sp.Text && bang_gio_hang.Rows[i]["id"].ToString() != id.Text)
                                    {
                                        bang_gio_hang.Rows.RemoveAt(i);
                                        break;
                                    }

                                }
                            }

                        }


                    }
                    dong["so_luong"] = sl;
                }

                // cap nhat lai STT
                int stt = 0;
                for (int i = 0; i <= bang_gio_hang.Rows.Count - 1; i++)
                {
                    stt += 1;
                    bang_gio_hang.Rows[i]["STT"] = stt;
                }


                bang_gio_hang.AcceptChanges();
                Session["gio_hang"] = bang_gio_hang;

                luoi_gio_hang.EditIndex = -1;
                xuat_luoi();
              //  Response.Redirect("Index.aspx?act=giohangx");
            }
            catch { }
        }

        protected void luoi_gio_hang_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "xoa")
            {
                try
                {
                    XL_Gio_hang bang_gio_hang = (XL_Gio_hang)Session["gio_hang"];
                    int d = luoi_gio_hang.Rows.Count - 1;
                    for (int i = 0; i <= luoi_gio_hang.Rows.Count - 1; i++)
                    {

                        CheckBox chon_xoa = (CheckBox)luoi_gio_hang.Rows[i].FindControl("CheckBox_xoa");
                        if (chon_xoa.Checked == true)
                        {
                        //    int ms = (int)luoi_gio_hang.DataKeys[i]["ID"];
                             Label id = new Label();
                            id = (Label)luoi_gio_hang.Rows[i].Cells[6].FindControl("lbl_id_");
                            DataRow dong_xoa = bang_gio_hang.Rows.Find(int.Parse(id.Text));
                            bang_gio_hang.Rows.Remove(dong_xoa);
                            if (i == d)
                            {
                                luoi_gio_hang.DataBind();
                                lbl_tongtien.Text = "0 VNĐ";
                                lbl_tongmathang.Text = "0";
                                lbl_tongsoluong.Text = "0";
                                break;
                            }
                        }
                    }
                    if (d != 0)
                    {
                        // cap nhat lai STT
                        int stt = 0;
                        for (int i = 0; i <= bang_gio_hang.Rows.Count - 1; i++)
                        {
                            stt += 1;
                            bang_gio_hang.Rows[i]["STT"] = stt;
                        }
                    }
                    Session["gio_hang"] = bang_gio_hang;
                    xuat_luoi();

                }
                catch { }
                //GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
            }
        }

                                  
        protected void ImageButton_ttmua_Click(object sender, ImageClickEventArgs e)
        {
            xuat_luoi();
            Response.Redirect("Index.aspx");
         //   ImageButton_ttmua.Attributes.Add("onClick", "javascript:history.back(); return false;");
        }

        //protected void ImageButton_xoa_Click(object sender, ImageClickEventArgs e)
        //{
           
        //    //Session["ok"] = "false";
        //   // xuat_luoi();
        //}

       
        protected void ImageButton_ttthanhtoan_Click(object sender, ImageClickEventArgs e)
        {
            this.Panel_thanhtoan.Visible = true;
            this.ImageButton_ttthanhtoan.Visible = false;
            Session["ok"] = "true";
        //    xuat_luoi();
        }

        protected void ImageButton_mua_Click(object sender, ImageClickEventArgs e)
        {
           // xuat_luoi();
                string gt = "";
                if (rd_nam.Checked == true)
                {
                    gt = "Nam";
                }
                else
                {
                    gt = "Nữ";
                }
                XL_Gio_hang bang_gio_hang = (XL_Gio_hang)Session["gio_hang"];
                DataTable tb = bang_gio_hang;
                // disable 2 nut huy va mau
                //this.ImageButton_mua.Visible = false;
                //this.ImageButton_huy.Visible = false;    
                if (tb.Rows.Count == 0)
                {
                    this.Panel_thanhtoan.Visible = false;   
                    this.lbl_thongbao.Text = "Time out ! Chưa có Sản phẩm nào !";
                    return;
                }
                StringBuilder str = new StringBuilder();
                str.Append("<table width='100%' style='border:1px solid #da0750;'>");
                str.Append("<tr style='color:#da0750'><td width='30'>STT</td><td>Tên sản phẩm</td><td>Giới tính</td><td>Size</td><td>Số lượng</td><td>Đơn giá</td><td>Thành tiền</td></tr>");
                for (int i = 0; i <= tb.Rows.Count - 1; i++)
                {
                    str.Append("<tr style='color:#da0750'><td width='30'>" + tb.Rows[i]["stt"].ToString() + "</td><td><a href='http://giarethoitrang.com/index.aspx?act=chitiet&id=" + tb.Rows[i]["id_sp"].ToString() + "&nid=" + tb.Rows[i]["id_nhom_sp"].ToString() + "&Gt=" + tb.Rows[i]["id_gt"].ToString() + "'>" + tb.Rows[i]["ten_sp"].ToString().Trim() + " (MS" + tb.Rows[i]["id_sp"].ToString() + ")</a></td><td>" + tb.Rows[i]["gioi_tinh_sp"].ToString() + "</td><td>" + tb.Rows[i]["so_size"].ToString() + "</td><td>" + tb.Rows[i]["so_luong"].ToString() + "</td><td>" + long.Parse(tb.Rows[i]["gia_sp"].ToString()).ToString("#,###") + "</td><td>" + long.Parse(tb.Rows[i]["thanh_tien"].ToString()).ToString("#,###") + "</td></tr>");
                }
                str.Append("</table>");
                str.Append("<table width='100%' style='border:1px solid #da0750;font-weight:bold'>");
                str.Append("<tr style='color:#da0750'><td>Tổng số mặt hàng: " + this.lbl_tongmathang.Text + "</td></tr>");
                str.Append("<tr style='color:#da0750'><td>Tổng số lượng: " + this.lbl_tongsoluong.Text + "</td></tr>");
                str.Append("<tr style='color:#da0750'><td>Tổng số tiền: " + this.lbl_tongtien.Text + "</td></tr>");
                str.Append("</table>");
              //  Session["thongbao"] = "Đơn hàng của quý khách đã gửi đi thành công. Chúng tôi sẽ liên hệ lại với quý khách sau 15 phút nữa ! Xin cảm ơn !";
               
                Email.sendMail(txt_hoten.Text.Trim(), gt, txt_diachi.Text.Trim(), txt_dienthoai.Text.Trim(), txt_email.Text, txt_thongtinthem.Text, str.ToString());

                this.lbl_thongbao.Text = "Đơn hàng của quý khách đã gửi đi thành công. Chúng tôi sẽ liên hệ lại với quý khách sau 15 phút nữa ! Xin cảm ơn !";
                this.Panel_thanhtoan.Visible = false;    
                this.lbl_giohang.Visible = false;
                this.Image_giohang.Visible = false;
                bang_gio_hang.Clear();
                Session["gio_hang"] = bang_gio_hang;
                xuat_luoi();
                GioHang gh = new GioHang();
                this.PreRender += new EventHandler(gh.GioHang_PreRender);
               
                          
           
        }

        protected void ImageButton_huy_Click(object sender, ImageClickEventArgs e)
        {
            this.ImageButton_ttthanhtoan.Visible = true;
            this.Panel_thanhtoan.Visible = false;
            Session["ok"] = "false";
        }

        protected void luoi_gio_hang_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            string path = System.Configuration.ConfigurationManager.AppSettings["Images_Path"];
           
            int i = int.Parse(Session["tooltip"].ToString());
            HyperLink tt = (HyperLink)e.Row.Cells[1].FindControl("link_tensp");
           if (e.Row.RowType == DataControlRowType.DataRow)
            {
                DataRowView drv = (DataRowView)e.Row.DataItem;
                i = i + 1;
                //e.Row.Attributes["data-tooltip"] = "sticky" +i + "";
                tt.Attributes["data-tooltip"] = "sticky" + i + "";
                tooltip.Append("<div id='sticky" + i + "' class='atip' style='width:200px'>");
                tooltip.Append("<img src='" + path + drv["hinh_anh"].ToString() + "' alt='' Width='190px' Height='210px'/>");
                tooltip.Append("</div>");
                lbl_tooltip.Text = tooltip.ToString();
                Session["tooltip"] = i;

                //Response.Redirect("Index.aspx?act=giohangx");
            }
           
                
        }



            
    }
}